<template>
  <div v-show="apiRes.payDataType == 'codeImgUrl'">
    <BasicModal
      v-bind="$attrs"
      @register="registerDrawer"
      :title="getTitle"
      width="330px"
      :height="330"
      :canFullscreen="false"
      @ok="handleSubmit"
      destroyOnClose
    >
      <div style="width: 100%; text-align: center">
        <!-- 自定义指令不能放到组件上，而是要放到自有的元素上,也就是这里用到的v-show不能放在自定义组件上 -->
        <img v-if="showQrCode && apiRes.payDataType == 'codeImgUrl'" :src="apiRes.payData" alt="" />
        <span v-else-if="apiRes.payDataType == 'payurl'"
          >等待用户支付 <hr /> 如浏览器未正确跳转请点击： <a :href="apiRes.payData" target="_blank">支付地址</a>
          <a-button size="small" class="copy-btn">复制链接</a-button>
        </span>
        <span v-else>等待用户支付,请稍后</span>
      </div>
      <div class="describe">
        <img src="/src/assets/svg/payTest/wx_app.svg" alt="" v-show="wxApp" /><!-- 微信图标 -->
        <img src="/src/assets/svg/payTest/ali_app.svg" alt="" v-show="aliApp" /><!-- 支付宝图标 -->
        <span>{{ payText }}</span>
      </div>
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed, useAttrs } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { useMessage } from "/@/hooks/web/useMessage"
  import LogoImg from "/@/assets/images/logo-small.png"
  import { QrCode } from "/@/components/Qrcode/index"
  import { useGlobSetting } from "/@/hooks/setting"
  import { connectWebSocket, onWebSocket } from "/@/hooks/web/useWebSocket"

  const { createMessage } = useMessage()
  const glob = useGlobSetting()

  // 声明Emits
  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const wxApp = ref(false) // 微信二维码图片是否展示
  const aliApp = ref(false) // 支付宝二维码图片是否展示
  const payText = ref("")
  const showQrCode = ref(false)
  const apiRes = ref<any>({}) // 接口返回数据包

  const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
    console.log("apiRes", data.apiRes)

    apiRes.value = {}
    wxApp.value = false
    aliApp.value = false
    apiRes.value = data.apiRes
    showQrCode.value = false
    const wayCode = data.wayCode

    // 根据不同的支付方式，展示不同的信息
    payText.value = ""
    if (wayCode === "WX_NATIVE" || wayCode === "WX_JSAPI") {
      // 微信二维码
      wxApp.value = true
      payText.value = '请使用微信"扫一扫"扫码支付'
    } else if (wayCode === "ALI_QR" || wayCode === "ALI_JSAPI") {
      // 支付宝二维码
      aliApp.value = true
      payText.value = '请使用支付宝"扫一扫"扫码支付'
    } else if (wayCode === "QR_CASHIER") {
      // 聚合支付二维码
      wxApp.value = true
      aliApp.value = true
      payText.value = "支持微信、支付宝扫码"
    }

    // h5 或者 wap
    if (wayCode === "WX_H5" || wayCode === "ALI_WAP") {
      payText.value = "请复制链接到手机端打开"
    } else {
      // 跳转到PC网站
      if (apiRes.value.payDataType === "  ") {
        window.open(apiRes.value.payData)
      }
    }
    showQrCode.value = true

    // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
    let url =
      glob.domainUrl?.replace("https://", "wss://").replace("http://", "ws://") +
      `/pay-ws-service/ws/payOrder/${apiRes.value.payOrderNo}/` +
      new Date().getTime()
    connectWebSocket(url)
    onWebSocket(onWebSocketMessage)
    console.log("建立websocket链接成功,url: ", url)
  })

  const onWebSocketMessage = (res) => {
    console.log("收到服务端推送: ", res)
    if (res.data.status === "2") {
      createMessage.success("支付成功, 2s后自动关闭...")
      setTimeout(() => {
        handleSubmit()
      }, 2000)
    } else {
      handleSubmit()
      createMessage.error(`支付失败, ${res.data.errCode}`)
    }
  }

  /**
   * 标题
   */
  const getTitle = computed(() => "支付体验")
  /**
   * 提交
   */
  async function handleSubmit() {
    try {
      setModalProps({ confirmLoading: true })
      closeModal()
      emit("success")
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>

<style lang="less" scoped>
  .describe {
    img {
      width: 30px !important;
      height: 30px !important;
    }

    display: flex;
    justify-content: center;
  }
</style>
